/**
* author: SamWu
* email：samwulqy@gmail.com
**/
<?php
header('Content-Type: application/json');
require_once '../includes/database.php';
require_once '../includes/security.php';

$response = ['success' => false, 'error' => null];

try {
    // 验证API凭证
    $apiKey = $_SERVER['HTTP_X_API_KEY'] ?? '';
    $secretKey = $_SERVER['HTTP_X_SECRET_KEY'] ?? '';
    
    if (empty($apiKey) || empty($secretKey)) {
        throw new Exception('Missing API credentials', 401);
    }
    
    $website = verifyApiCredentials($apiKey, $secretKey);
    
    // 解析请求
    $action = $_GET['action'] ?? '';
    $input = json_decode(file_get_contents('php://input'), true) ?? [];
    
    switch ($action) {
        case 'get_stats':
            $stats = getWebsiteStats($website['id']);
            $response = ['success' => true, 'data' => $stats];
            break;
            
        case 'update_limits':
            $newLimit = intval($input['monthly_max_requests'] ?? 0);
            if ($newLimit < 1000 || $newLimit > MAX_MONTHLY_REQUESTS) {
                throw new Exception('Invalid limit value', 400);
            }
            
            $currentMonth = date('Ym');
            $stmt = $pdo->prepare("UPDATE request_stats 
                                  SET monthly_max_requests = ? 
                                  WHERE website_id = ? AND current_month = ?");
            $stmt->execute([$newLimit, $website['id'], $currentMonth]);
            
            $response = ['success' => true, 'new_limit' => $newLimit];
            break;
            
        case 'generate_key':
            $apiKey = generateSecureRandom(32);
            $secretKey = generateSecureRandom(64);
            
            $stmt = $pdo->prepare("INSERT INTO api_keys 
                                  (website_id, api_key, secret_key) 
                                  VALUES (?, ?, ?)");
            $stmt->execute([$website['id'], $apiKey, $secretKey]);
            
            $response = [
                'success' => true,
                'api_key' => $apiKey,
                'secret_key' => $secretKey
            ];
            break;
            
        case 'revoke_key':
            $keyToRevoke = sanitizeInput($input['api_key'] ?? '');
            if (empty($keyToRevoke)) {
                throw new Exception('Missing API key', 400);
            }
            
            $stmt = $pdo->prepare("UPDATE api_keys 
                                  SET is_active = FALSE 
                                  WHERE api_key = ? AND website_id = ?");
            $stmt->execute([$keyToRevoke, $website['id']]);
            
            $response = ['success' => true, 'revoked_key' => $keyToRevoke];
            break;
            
        case 'verify_token':
            $token = sanitizeInput($input['token'] ?? '');
            if (empty($token)) {
                throw new Exception('Missing token', 400);
            }
            
            $tokenData = verifyToken($token);
            if (!$tokenData || $tokenData['website_id'] != $website['id']) {
                throw new Exception('Invalid token', 400);
            }
            
            $response = [
                'success' => true,
                'valid' => true,
                'issued_at' => $tokenData['created_at'],
                'ip_address' => $tokenData['ip_address']
            ];
            break;
            
        case 'activate':
            $domain = sanitizeInput($input['domain'] ?? '');
            $maxRequests = intval($input['monthly_max_requests'] ?? 10000);
            $email = sanitizeInput($input['contact_email'] ?? '');
            
            if (empty($domain) || empty($email)) {
                throw new Exception('Missing required fields', 400);
            }
            
            // 生成VUID
            $vuid = generateSecureRandom(36);
            
            // 创建网站记录
            $stmt = $pdo->prepare("INSERT INTO websites 
                                  (domain, vuid, contact_email, callback_url) 
                                  VALUES (?, ?, ?, ?)");
            $stmt->execute([
                $domain,
                $vuid,
                $email,
                $input['callback_url'] ?? ''
            ]);
            $websiteId = $pdo->lastInsertId();
            
            // 初始化统计
            $currentMonth = date('Ym');
            $stmt = $pdo->prepare("INSERT INTO request_stats 
                                  (website_id, monthly_max_requests, current_month) 
                                  VALUES (?, ?, ?)");
            $stmt->execute([$websiteId, $maxRequests, $currentMonth]);
            
            // 生成主API密钥
            $apiKey = generateSecureRandom(32);
            $secretKey = generateSecureRandom(64);
            
            $stmt = $pdo->prepare("INSERT INTO api_keys 
                                  (website_id, api_key, secret_key, is_primary) 
                                  VALUES (?, ?, ?, 1)");
            $stmt->execute([$websiteId, $apiKey, $secretKey]);
            
            $response = [
                'success' => true,
                'vuid' => $vuid,
                'api_key' => $apiKey,
                'secret_key' => $secretKey,
                'monthly_max_requests' => $maxRequests
            ];
            break;
            
        default:
            throw new Exception('Invalid action', 400);
    }
    
} catch (Exception $e) {
    $response['error'] = $e->getMessage();
    http_response_code($e->getCode() ?: 400);
}

echo json_encode($response);
?>
